package org.zjt.thread;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @author juntao.zhang
 * @version V1.0
 * @Description: TODO
 * @Package org.zjt.thread
 * @date 2018/6/4 22:28
 */
@Slf4j
public class FutureTest {

    private static final SimpleAsyncTaskExecutor SIMPLE_ASYNC_TASK_EXECUTOR = new SimpleAsyncTaskExecutor();

    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(4);



    public static void main(String[] args) throws InterruptedException {

        // jdk 版本异步回调实现
        Consumer<String> callback = a -> log.info("接受得到的结果，并利用观察者模式回调:{}",a);
        EXECUTOR_SERVICE.submit(() -> {
            log.info("-------------------------do something----------------------------");

            // 执行回调通知（类似观察者）
            callback.accept("1");
        });


        // spring 异步回调实现
        ListenableFuture<Integer> listenableFuture = SIMPLE_ASYNC_TASK_EXECUTOR.submitListenable(() -> 1);
        listenableFuture.addCallback(new ListenableFutureCallback<Integer>() {
            @Override
            public void onSuccess(Integer o) {
                log.info("接受得到的结果，并利用观察者模式回调:{}",o);
            }

            @Override
            public void onFailure(Throwable throwable) {
                log.error("接受得到的结果",throwable);
            }
        });

        Thread.currentThread().join(1000);
        EXECUTOR_SERVICE.shutdown();
    }
}
